<script setup lang="ts">
  import { reactive, onMounted, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router' 
  import { routeList } from '@/router/routes';

  interface routesType {
    path: string;
    meta: {
      title: string;
      [propName: string]: string;
    }
    children?: routesType[]
  }

  const route = useRoute();
  const router = useRouter();

  interface breadListItemType {
    path: string;
    name: string;
  }
  const breadList: breadListItemType[] = [];
  const data = reactive({ breadList })

  // 生成层级列表数据
  const getBreadList = () => {
    data.breadList = [];
    const path = route.path
    const pathList: string[] = []
    path.split('/').reduce((parentPath, childPath) => {
        pathList.push(parentPath + '/' + childPath)
        return parentPath + '/' + childPath;
    })
    
    // 移除第一个父级元素
    pathList.shift();
    for (let i = 0; i < pathList.length; i++) {
      const currentPath = pathList[i];
      let name = getName(currentPath, routeList as unknown as routesType[]);
      
      // 未查询到name，说明对应路径不存在路由
      if (name) {
        data.breadList.push({ name, path: currentPath })
      }
    }
  }

  const getName = (path: string, routes: routesType[]): string => {
    let name = ''
    for (let item of routes) {
      if (item.path === path) {
        name = item.meta.title
        break
      }
      if (item.children) {
        let res = getName(path, item.children)
        if (res) {
          name = res
          break
        }
      }
    }
    return name
  }

  // 路由变化，更新面包屑
  watch(
    () => route.path,
    () => {
      getBreadList();
    }
  )

  onMounted(() => {
    getBreadList();
  })
</script>
<template>
  <div class="crumbs-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item
        v-for="(item, index) in data.breadList"
        :key="index"
        :to="index == 0 ? item.path : ''"
      >
        {{ item.name }}
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<style scoped>
.crumbs-container {
  position: absolute;
  top: 90px;
  left: 200px;
  width: calc(100% - 220px);
  height: 40px;
  padding-left: 20px;
  z-index: 4;
  background: #f0f0f0;
}
.crumbs-container :deep(.el-breadcrumb) {
  line-height: 40px;
}
</style>